<?php
namespace Admin\Controller;
use Think\Controller;
/*
	微信相关设置
*/
class WechatsController extends InitController {
	

	/* 设置微信基本信息 */
	public function Setting(){
		
		if(IS_AJAX){
			$name = I('post.name');
			$account = I('post.account');
			$original = I('post.original');
			$wetoken = I('post.wetoken');
			$secret = I('post.secret');
			$key = I('post.key');

			if (empty($name)) {
				$this->error('抱歉，请填写公众号名称！');
			}
	
			$encrypt_mode = I('post.encrypt_mode');
			$EncodingAESKey = trim(I('post.encodingaeskey'));
			if($encrypt_mode == 1 || $encrypt_mode == 2){
				if($EncodingAESKey == ''){
					$this->error('请填写EncodingAESKey！');
				}
			}
			
			$data = array(
				'name' => $name,
				'account' => $account,
				'original' => trim($original),
				'token' => $wetoken ? $wetoken : random(32),
				'appid' => trim($key),
				'appsecret' => trim($secret),
				'encodingaeskey'=>$EncodingAESKey,//aes密钥
				'encrypt_mode'=>$encrypt_mode,//模式，0-明文,1-兼容，2-安全
				'access_token'=>'',
				'access_jsapi'=>'',
			);
			
			//获取access_token
			import('Vendor.Wechat.access');
			$wechat = new \WechatAccess();
			$accesstoken = $wechat->account_token(false); //重新生成access_token
			$data['access_token'] = $accesstoken;
			
			//序列化数组
			$data = serialize($data);
			//微信参数
			$option =array(
				'option_name'=>'weixin_array',
				'option_value'=>$data,
			);
			
			$array = D('Options')->getOpts(array('option_name'=>'weixin_array'));
			if(!empty($array)){
				$ac = M('Options')->where(array('option_name'=>'weixin_array'))->save($option);
			}else{
				$ac = M('Options')->add($option);
			}
		
			$this->ajaxReturn(array('error'=>0,'errmsg'=>'更新公众号成功'));
		}
		
		//寻找信息
		$array = D('Options')->getOpts(array('option_name'=>'weixin_array'));
		$wechat = unserialize($array['weixin_array']);

		$topmenu = $this->topmenu;
		$sidebarmenu = $this->sidebarmenu[I('get.k')];
		
		$this->assign(array(
			'wechat' => $wechat,
			'topmenu'=>$topmenu,
			'sidebarmenu'=>$sidebarmenu
		));
		$this->display("Setting");
	}
	
	
	
	/* 显示微信自定义菜单 */
	public function MenuDisplay(){
			
		if(IS_AJAX){
			
			//同步更新微支付参数
			$appid = trim(I('post.appid'));
			$appsecret = trim(I('post.appsecret'));
			if(!empty($appid) && !empty($appsecret)){
				$data = array('appid'=>$appid,'appsecret'=>$appsecret);
                $weixin_array = M('Options')->where(array('option_name'=>'weixin_array'))->find();

                $weixin_array = unserialize($weixin_array['option_value']);
                $weixin_array['appid'] = $appid;
                $weixin_array['appsecret'] = $appsecret;
                $weixin_array = serialize($weixin_array);
                
                if($weixin_array){
                    $ins = M('Options')->where(array('option_name'=>'weixin_array'))->save(array('option_value'=>$weixin_array));
                }else{
                    $datas = array(
                        'option_value'=>serialize($data),
                        'option_name'=>'weixin_array',
                    );
                    $ins = M('Options')->add($datas);         
                }
                
				if($ins){
					exit('1');
				}else{
					exit('2');
				}
			}
		}
        
		$account  = D('Options')->getOpts(array('option_name'=>'weixin_array'));
		$menudata = D('Options')->getOpts(array('option_name'=>'weixin_menu'));

		//$account = M('Wechats')->where(1)->field('appid,appsecret')->find();
		//$menudata = M('WechatsMenu')->getField('data');
		//
		/*if(empty($menudata)){
			M('Options')->add(array('option_name'=>''));
		}*/
        
		//解序列化并解JSON模式
		if(!empty($menudata) || !empty($account)){
			$menus  = json_decode($menudata['weixin_menu'],1);
            $account = unserialize($account['weixin_array']);
		}
  
		/* $dat = htmlspecialchars_decode($menudata);
		$menus = @json_decode($dat, true); */

		if(is_array($menus['menu']['button'])) {
			$pregmatch='/[\x7f-\xff]/';
			foreach($menus['menu']['button'] as &$m) {
				if($m['key']) {
					$m['forward'] = $m['key'];
				}
				//对url的中文进行base64
				if(isset($m['url'])){
					$url = parse_url($m['url']);
					if(count($url) > 1){
						foreach($url as $k => $v){
							if (preg_match($pregmatch, $v)) {
								$a = convertUrlQuery($v);
								foreach($a as $kk=>$vv){
									$a[$kk] = urlencode($vv);
								}
								$url[$k] = getUrlQuery($a);
							}
						}
						$m['url'] = unparse_url($url);
					}
				}
				
				if(is_array($m['sub_button'])) {
					foreach($m['sub_button'] as &$s) {
						$s['forward'] = $s['key'];
						//对url的中文进行base64
						if(isset($s['url'])){
							//var_dump($s['url']);
							$url = parse_url($s['url']);
						
							if(count($url) > 1){
								foreach($url as $k => $v){
									if (preg_match($pregmatch, $v)) {
										$a = convertUrlQuery($v);
										foreach($a as $kk=>$vv){
											$a[$kk] = urlencode($vv);
										}
										$url[$k] = getUrlQuery($a);
									}
								}
								$s['url'] = unparse_url($url);
								
							}
						}
					}
				}
			}
		}
		
		$topmenu = $this->topmenu;
		$sidebarmenu = $this->sidebarmenu[I('get.k')];
		
		$this->assign(array(
			'menus'=>$menus,
			'account'=>$account,
			'topmenu'=>$topmenu,
			'sidebarmenu'=>$sidebarmenu
		));
		$this->display('MenuDisplay');
	}
	
	/* 
		生成微信自定义菜单
	*/
	public function MenuPost(){
		if(!IS_POST){
			$this->error('出错了哦！');
		}
		$gateway = array();
		$gateway['get'] = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s";
		$gateway['create'] = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s";
		$gateway['delete'] = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s";
            
		$weid = session('weid');
		$mDat = $_POST['do'];
	    $menus = json_decode($mDat,true);   

		if(!is_array($menus)) {
			$this->error('操作非法.');
		}
        
		foreach($menus as &$m) {
			if(mb_strlen($m['name'],'utf-8') > 5){
				$this->error('主菜单的名称长度不能超过5个字');
			}
			$m['name'] = urlencode(trim($m['name']));
			if(is_array($m['sub_button'])) {
				foreach($m['sub_button'] as &$s) {
					if(mb_strlen($s['name'],'utf-8') > 8){
						$this->error('子菜单的名称长度不能超过8个字');
					}
					$s['name'] = urlencode(trim($s['name']));
					if(isset($s['url'])){
						$s['url'] = trim($s['url']);
					}
				}
			}
		}
		$mf =$ms = array();
		$mf['menu']['button'] =$ms['button'] = $menus;

		$savesqldat = json_encode($mf);
		$savesqldat = urldecode($savesqldat);
        $menudata = D('Options')->getOpts(array('option_name'=>'weixin_menu'));
      
        if(empty($menudata)){
            $data = array(
                'option_value'=>$savesqldat,
                'option_name'=>'weixin_menu',
            );
            M('Options')->add($data);    
        }else{
            M('Options')->where(array('option_name'=>'weixin_menu'))->save(array('option_value'=>$savesqldat));            
        }
		//M('Wechats')->where(1)->save(array('access_token'=>''));
        //M('WechatsMenu')->where(1)->save(array('data'=>$savesqldat));
        
		$dat = json_encode($ms);

		$dat = urldecode($dat);
		
		import('Vendor.Wechat.access');
		$wechat = new \WechatAccess();
		$token = $wechat->account_token();
		$url = sprintf($gateway['create'], $token);
		$curl = new  \Org\Util\Curl;
		$content=@$curl->ihttp_request($url,$dat);

		$dat = $content['content'];
		$result = @json_decode($dat, true);
		if($result['errcode'] == '0') {
			$this->success('已经成功创建菜单. ', U('Wechats/MenuDisplay',array('k'=>'9','sk'=>'1')));
		} else {
			$this->error("公众平台返回接口错误. <br />错误代码为: {$result['errcode']} <br />错误信息为: {$result['errmsg']} <br />错误描述为: " . $result['errcode']);
		}


	}
	
	
	/* 分销通知设置 */
	 public function Wxnotify(){
		
		$row = M('Wxnotify')->where(1)->find();
		$wxtemp = M('Wxtemplate')->where(1)->field('template_id,template_id_short')->select(array(),'template_id_short');
	
		//判断模板id
		if(!empty($wxtemp)){
			foreach($wxtemp as $k=>$v){
				$wxtemp[$v['template_id_short']] = $v;
			}
		}
	
		if(IS_AJAX){
			$up =  array(
					'finish'=>I('finish'),
					'register'=>I('register'),
				);
			if($row){
				$oregister = $row['register'] ? '开启' : '关闭';
				$ofinish = $row['finish'] ? '开启' : '关闭';
				$register = $up['register'] ? '开启' : '关闭';
				$finish = $up['finish'] ? '开启' : '关闭';
				$content = "微信消息通知设置：<br/>旧设置：发展下线通知：{$oregister},付款佣金订单通知：{$ofinish};";
				$content .= "<br/>新设置：发展下线通知：{$register},付款佣金订单通知：{$finish};";
				$ac = M('Wxnotify')->where(1)->save($up);
			}else{
				$ac = M('Wxnotify')->add($up);
				$register = $up['register'] ? '开启' : '关闭';
				$finish = $up['finish'] ? '开启' : '关闭';
				$content = "微信消息通知设置：发展下线通知：{$register},付款佣金订单通知：{$finish};";
			}

			$order = I('OPENTM205211943');
			$fans  = I('OPENTM203264949');
			$orderconfirm = I('TM00781');
			if($order){
				$content .= "<br/>销订单提成通知id：{$order}";
				if(empty($wxtemp['OPENTM205211943'])){
					$wxtemp = array(
						'template_id'=>$order,
						'template_id_short'=>'OPENTM205211943',
						'createtime'=>NOW_TIME,
					);
					$waco = M('Wxtemplate')->add($wxtemp);
				}else{
					$waco = M('Wxtemplate')->where(array('template_id_short'=>'OPENTM205211943'))->save(array('template_id'=>$order));
				}
			}
			if($fans){
				$content .= "<br/>成为会员通知id：{$fans}";
				if(empty($wxtemp['OPENTM203264949'])){
					$wxtemp = array(
						'template_id'=>$fans,
						'template_id_short'=>'OPENTM203264949',
						'createtime'=>NOW_TIME,
					);
					$waco = M('Wxtemplate')->add($wxtemp);
				}else{
					$wact = M('Wxtemplate')->where(array('template_id_short'=>'OPENTM203264949'))->save(array('template_id'=>$fans));
				}
			}
			if($orderconfirm){
				$content .= "<br/>订单确认通知id：{$orderconfirm}";
				if(empty($wxtemp['TM00781'])){
					$wxtemp = array(
						'template_id'=>$orderconfirm,
						'template_id_short'=>'TM00781',
						'createtime'=>NOW_TIME,
					);
					$waco = M('Wxtemplate')->add($wxtemp);
				}else{
					$wact = M('Wxtemplate')->where(array('template_id_short'=>'TM00781'))->save(array('template_id'=>$orderconfirm));
				}
			}
			if($ac !==false || $waco !== false || $wact !== false){
				//ActionLog(null,$content,'wxnotify');
				$this->success('更新成功');
			}
			$this->error('操作失败');
		}
		
		$topmenu = $this->topmenu;
		$sidebarmenu = $this->sidebarmenu[I('get.k')];
		
		
		$this->assign(array(
			'row'=>$row,
			'wxtemp'=>$wxtemp,
			'topmenu'=>$topmenu,
			'sidebarmenu'=>$sidebarmenu
		));
		
		$this->display('wxNotify');
	} 
	
	
	/*
		重置微信消息模板
	*/
	/* public function Regwxtemplate(){
		
		if(!IS_AJAX){
			$this->error('出错了哦！~');
		}
		
		M('Wxtemplate')->where(1)->delete();
		
		import('Vendor.Wechat.access');
		$wechat = new \WechatAccess();
		//获取消息模板
		$accesstoken = $wechat->account_token();
		$url = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token={$accesstoken}";
		$sendcontent = array(
			'industry_id1'=>'31',
			'industry_id2'=>'41',
		);
	
		$curl = new  \Org\Util\Curl;
		$returnihttp = $curl->ihttp_request($url,json_encode($sendcontent));

		//{"errcode":0,"errmsg":"ok"} , {"errcode":43100,"errmsg":"change template too frequently"}   存在两个状态
		
		//OPENTM205160490 商品支付通知	//OPENTM203264949 成为会员通知  //TM00781 订单确认通知
		
		$tempid = array("OPENTM205160490",'OPENTM203264949','TM00781');
		$content = "重置消息模版：";
		foreach($tempid as $key){
			$url = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={$accesstoken}";
			$sendcontent = array(
				'template_id_short'=>$key,
			);
			$tempinfo = $curl->ihttp_request($url,json_encode($sendcontent));
			$tempinfocontent = json_decode($tempinfo['content'],true);
			$wxtemp = array(
				'template_id'=>$tempinfocontent['template_id'],
				'template_id_short'=>$key,
				'createtime'=>NOW_TIME,
			);
			M('Wxtemplate')->add($wxtemp);
			if($key == 'OPENTM205160490'){
				$content .= "商品支付通知id：{$tempinfocontent['template_id']}；";
			}elseif($key == 'OPENTM203264949'){
				$content .= "成为会员通知id：{$tempinfocontent['template_id']}；";
			}elseif($key == 'OPENTM203264949'){
				$content .= "订单确认通知id：{$tempinfocontent['template_id']}；";
			}
		}
		//ActionLog(null,$content,'regwxtemplate');
		$this->success("操作成功");
	} */
	
	
}	